package cn.jsxz.common.utils.WeiXinUtil;


import cn.jsxz.common.utils.EmojiUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;


public class weixinutils {

    /**
     * 获取请求用户信息的access_token
     *
     * @param code
     * @return
     */
    public static Map<String, String> getUserInfoAccessToken(String code, String appid, String AppSecret) {
        System.out.println("code================" + code);
        System.out.println("appid================" + appid);
        System.out.println("AppSecret================" + AppSecret);
        JsonObject object = null;
        Map<String, String> data = new HashMap<>();
        try {
            String url = String.format("https://api.WeiXinUtil.qq.com/sns/oauth2/access_token?appid=%s&secret=%s&code=%s&grant_type=authorization_code",
                    appid, AppSecret, code);
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpGet httpGet = new HttpGet(url);
            HttpResponse httpResponse = httpClient.execute(httpGet);
            HttpEntity httpEntity = httpResponse.getEntity();
            String tokens = EntityUtils.toString(httpEntity, "utf-8");
            Gson token_gson = new Gson();
            object = token_gson.fromJson(tokens, JsonObject.class);
            data.put("openid", object.get("openid").toString().replaceAll("\"", ""));
            data.put("access_token", object.get("access_token").toString().replaceAll("\"", ""));
        } catch (Exception ex) {
            System.out.println("授权失败");
            ex.printStackTrace();
        }
        return data;
    }

    /**
     * 网页授权获取用户信息
     * 获取用户信息
     *
     * @param accessToken 网页授权获取的 token
     * @param openId
     * @return
     */
    public static Map<String, String> getAutoUserInfo(String accessToken, String openId) {
        Map<String, String> data = new HashMap();
        String url = "https://api.WeiXinUtil.qq.com/sns/userinfo?access_token=" + accessToken + "&openid=" + openId + "&lang=zh_CN";
        JsonObject userInfo = null;
        try {
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpGet httpGet = new HttpGet(url);
            HttpResponse httpResponse = httpClient.execute(httpGet);
            HttpEntity httpEntity = httpResponse.getEntity();
            String response = EntityUtils.toString(httpEntity, "utf-8");
            Gson token_gson = new Gson();
            userInfo = token_gson.fromJson(response, JsonObject.class);
            data.put("openid", userInfo.get("openid").toString().replaceAll("\"", ""));
            data.put("sex", userInfo.get("sex").toString().replaceAll("\"", ""));
            String nickname = userInfo.get("nickname").toString().replaceAll("\"", "");
//            String  pattern="(?:[\uD83C\uDF00-\uD83D\uDDFF]|[\uD83E\uDD00-\uD83E\uDDFF]|[\uD83D\uDE00-\uD83D\uDE4F]|[\uD83D\uDE80-\uD83D\uDEFF]|[\u2600-\u26FF]\uFE0F?|[\u2700-\u27BF]\uFE0F?|\u24C2\uFE0F?|[\uD83C\uDDE6-\uD83C\uDDFF]{1,2}|[\uD83C\uDD70\uD83C\uDD71\uD83C\uDD7E\uD83C\uDD7F\uD83C\uDD8E\uD83C\uDD91-\uD83C\uDD9A]\uFE0F?|[\u0023\u002A\u0030-\u0039]\uFE0F?\u20E3|[\u2194-\u2199\u21A9-\u21AA]\uFE0F?|[\u2B05-\u2B07\u2B1B\u2B1C\u2B50\u2B55]\uFE0F?|[\u2934\u2935]\uFE0F?|[\u3030\u303D]\uFE0F?|[\u3297\u3299]\uFE0F?|[\uD83C\uDE01\uD83C\uDE02\uD83C\uDE1A\uD83C\uDE2F\uD83C\uDE32-\uD83C\uDE3A\uD83C\uDE50\uD83C\uDE51]\uFE0F?|[\u203C\u2049]\uFE0F?|[\u25AA\u25AB\u25B6\u25C0\u25FB-\u25FE]\uFE0F?|[\u00A9\u00AE]\uFE0F?|[\u2122\u2139]\uFE0F?|\uD83C\uDC04\uFE0F?|\uD83C\uDCCF\uFE0F?|[\u231A\u231B\u2328\u23CF\u23E9-\u23F3\u23F8-\u23FA]\uFE0F?)";
            String reStr = "";
//            Pattern  emoji=Pattern.compile(pattern);
//            Matcher  emojiMatcher=emoji.matcher(nickname);
//            nickname=emojiMatcher.replaceAll(reStr);
            if (nickname != null && !nickname.equals("")) {
                data.put("nickname", EmojiUtil.changeToByte(nickname));
            }
            data.put("city", userInfo.get("city").toString().replaceAll("\"", ""));
            data.put("province", userInfo.get("province").toString().replaceAll("\"", ""));
            data.put("country", userInfo.get("country").toString().replaceAll("\"", ""));
            data.put("headimgurl", userInfo.get("headimgurl").toString().replaceAll("\"", ""));
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return data;
    }


    /**
     * 微信平台开发者 获取access_token
     *
     * @param wx_appid
     * @param wx_appsecret
     * @return
     */
    @SuppressWarnings({"deprecation", "resource"})
    public static Map<String, String> getAccessToken(String wx_appid, String wx_appsecret) {
        @SuppressWarnings({"unchecked", "rawtypes"})
        Map<String, String> data = new HashMap();
        String url = "https://api.WeiXinUtil.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + wx_appid + "&secret=" + wx_appsecret;
        JsonObject accessTokenInfo = null;
        try {
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpGet httpGet = new HttpGet(url);
            HttpResponse httpResponse = httpClient.execute(httpGet);
            HttpEntity httpEntity = httpResponse.getEntity();
            String response = EntityUtils.toString(httpEntity, "utf-8");
            System.out.println("获取Token-------------------" + response);
            Gson token_gson = new Gson();
            accessTokenInfo = token_gson.fromJson(response, JsonObject.class);
            data.put("access_token", accessTokenInfo.get("access_token").toString().replaceAll("\"", ""));
            data.put("expires_in", accessTokenInfo.get("expires_in").toString().replaceAll("\"", ""));
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return data;
    }


    /**
     * 获取jsapi_ticket
     *
     * @return
     */
    public static Map<String, String> getJsApiTicket(String accessToken) {
        Map<String, String> data = new HashMap();
        String url = "https://api.WeiXinUtil.qq.com/cgi-bin/ticket/getticket?access_token=" + accessToken + "&type=jsapi";
        JsonObject jsApiTicket = null;
        try {
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpGet httpGet = new HttpGet(url);
            HttpResponse httpResponse = httpClient.execute(httpGet);
            HttpEntity httpEntity = httpResponse.getEntity();
            String response = EntityUtils.toString(httpEntity, "utf-8");
            Gson token_gson = new Gson();
            jsApiTicket = token_gson.fromJson(response, JsonObject.class);
            data.put("ticket", jsApiTicket.get("ticket").toString().replaceAll("\"", ""));
            data.put("expires_in", jsApiTicket.get("expires_in").toString().replaceAll("\"", ""));

        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return data;
    }


    /**
     * 全局Token 获取用户信息
     * 获取微信公众号用户的基本信息(UnionID机制)
     *
     * @param accessToken
     * @param openId
     * @return
     */
    @SuppressWarnings({"deprecation", "unused"})
    public static Map<String, String> getUserInfo(String accessToken, String openId) {
        @SuppressWarnings({"rawtypes", "unchecked"})
        Map<String, String> data = new HashMap();
        // String url = "https://api.weixin.qq.com/sns/userinfo?access_token=" + accessToken + "&openid=" + openId + "&lang=zh_CN";
        String url = "https://api.WeiXinUtil.qq.com/cgi-bin/user/info?access_token=" + accessToken + "&openid=" + openId + "&lang=zh_CN";
        JsonObject userInfo = null;
        try {
            @SuppressWarnings("resource")
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpGet httpGet = new HttpGet(url);
            HttpResponse httpResponse = httpClient.execute(httpGet);
            HttpEntity httpEntity = httpResponse.getEntity();
            String response = EntityUtils.toString(httpEntity, "utf-8");

            Gson token_gson = new Gson();

            userInfo = token_gson.fromJson(response, JsonObject.class);
            System.out.println(userInfo.toString());
            if (userInfo == null) {
                data.put("subscribe", "0");
            } else {
                data.put("subscribe", userInfo.get("subscribe").toString().replaceAll("\"", ""));
            }

        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return data;
    }


    public static void main(String[] args) {
//	    Map<String, String> map = 	weixinutils.getAccessToken("wx0bf0d507841d59f9", "73a95ab5c6a24eb830f3cebf47b7619c");
//	    System.out.println(map.get("access_token"));
        // Map<String, String> maps = 	weixinutils.getJsApiTicket("11_fPUFJoA4sL_o7P8lqrpF2MmWIGpgxXahusPlv4aL5RSxidcrocc-KBglDRQFH9kffDAombrctefdO039zmtXe_Q3VvNcqlrWcHjJiTSOE6PnN03Ka2Mf7FJn1t0IVcrr77QOeGvMW5CUzhk0FPYfABASCL");
        //  System.out.println(maps.toString());

        //Map<String, String> data =	weixinutils.getUserInfo("10_iAXqdj6qUEqRrm0o3HGrPuXopE0-umZ2j5fhQjlynXZSJ2BrOa2Ay8QHt41ua8ItoxHVxvQda4PPa3hWuVstJ2cwV1G6XS9G3PLP66dajn1JV8stRohtqGprv-0j7FuxMFlWjty51e6SDHA9RLCbAJAEYP", "oGzeXwHBHSlNPJEvQNiqz3OM5LpY1");
        // System.out.println(data.toString());

        TreeMap<String, String> paramss = new TreeMap<String, String>();
        paramss.put("ticket", "HoagFKDcsGMVCIY2vOjf9k0g9yqFy2-w5-eFTyaww9s2e2AvCKS-0w6-s8qoOq9xbRb4nVfCaJng-w94rMuk-A");
        WeiXinResult result = HttpRequestUtil.downMeaterMetod(paramss, HttpRequestUtil.GET_METHOD, "https://mp.WeiXinUtil.qq.com/cgi-bin/showqrcode", "D:\\test.png");
        System.out.println(result);
    }


    /**
     * 创建菜单
     */
    public static String createMenu(String params, String accessToken) throws Exception {
        HttpPost httpost = new HttpPost("https://api.WeiXinUtil.qq.com/cgi-bin/menu/create?access_token=" + accessToken);
        httpost.setEntity(new StringEntity(params, "UTF-8"));
//		HttpResponse response = httpclient.execute(httpost);
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpResponse response = httpClient.execute(httpost);
        String jsonStr = EntityUtils.toString(response.getEntity(), "utf-8");
        JSONObject object = JSON.parseObject(jsonStr);
        return object.getString("errmsg");
    }





    /* *//**
     * 获取access_token 
     * @param appid 凭证 
     * @param appsecret 密钥 
     * @return
     *//*  
    public static String getAccessToken(String appid, String appsecret) {  
        String result = HttpRequestUtil.getAccessToken(appid,appsecret);  
        JSONObject jsonObject = JSONObject.fromObject(result);  
        if (null != jsonObject) {  
            try {  
                result = jsonObject.getString("access_token");  
            } catch (JSONException e) {  
               logger.info("获取token失败 errcode:"+jsonObject.getInt("errcode") +",errmsg:"+ jsonObject.getString("errmsg"));                
            }  
        }  
        return result;  
    }  
    */


}
